Popular Searches
Popular Course Categories
Popular Courses

Class Name

Selenium Locators

<div class="selenium-notes">

<h1>Class Name Locator in Selenium</h1>

<p>The <strong>Class Name Locator</strong> is one of the standard locator strategies provided by Selenium WebDriver for identifying web elements using the value of their HTML <code>class</code> attribute. It is useful when an element does not have a suitable unique ID or when multiple elements belong to the same CSS class.</p>

<p>In Selenium Java, the Class Name Locator is implemented using <code>By.className()</code>. For example, if an HTML element contains <code>class="username"</code>, Selenium can locate it using <code>driver.findElement(By.className("username"))</code>.</p>

<p>Locators are an important part of Selenium WebDriver because Selenium must identify the correct WebElement before performing actions such as <code>click()</code>, <code>sendKeys()</code>, <code>clear()</code>, <code>getText()</code>, and attribute validation. JustAcademy's Selenium training curriculum includes different locator strategies such as ID, Name, Class Name, XPath, and CSS Selectors for locating and interacting with web elements. :contentReference[oaicite:0]{index=0}</p>

<p>Learn more through the <a href="https://www.justacademy.co/course-detail/selenium-training" target="_blank" rel="noopener noreferrer">JustAcademy's Selenium Training Course</a> and explore the <a href="https://www.justacademy.co/register-for-course-demo" target="_blank" rel="noopener noreferrer">Selenium Course Demo Registration</a>.</p>

<hr>

<h2>1. What is a Class Name Locator?</h2>

<p>A Class Name Locator identifies a web element by using the value of its HTML <code>class</code> attribute.</p>

<p>The basic Selenium Java syntax is:</p>

<pre><code>driver.findElement(By.className("classValue"));</code></pre>

<p>For example:</p>

<pre><code>&lt;input type="text" class="username"&gt;</code></pre>

<p>The element can be located using:</p>

<pre><code>driver.findElement(By.className("username"));</code></pre>

<hr>

<h2>2. Understanding the HTML Class Attribute</h2>

<p>The <code>class</code> attribute is commonly used in HTML for applying CSS styles, grouping related elements, and identifying elements that share a common design or behavior.</p>

<p>Example:</p>

<pre><code>&lt;input type="text" class="form-control"&gt;</code></pre>

<p>Here, <code>form-control</code> is the value of the <code>class</code> attribute.</p>

<p>Selenium can use this value with:</p>

<pre><code>By.className("form-control")</code></pre>

<hr>

<h2>3. Syntax of Class Name Locator</h2>

<p>The Selenium Java syntax is:</p>

<pre><code>By.className("classValue")</code></pre>

<p>With <code>findElement()</code>:</p>

<pre><code>WebElement element = driver.findElement(By.className("classValue"));</code></pre>

<p>Example:</p>

<pre><code>WebElement username = driver.findElement(By.className("username"));</code></pre>

<hr>

<h2>4. Simple Class Name Example</h2>

<p>Consider the following HTML:</p>

<pre><code>&lt;input type="text" class="username"&gt;</code></pre>

<p>Selenium code:</p>

<pre><code>driver.findElement(By.className("username")).sendKeys("admin");</code></pre>

<p>Selenium searches the page for an element whose class attribute contains the specified class token.</p>

<hr>

<h2>5. Class Name Locator with Username Field</h2>

<pre><code>&lt;input type="text" class="username" placeholder="Enter Username"&gt;</code></pre>

<pre><code>driver.findElement(By.className("username")).sendKeys("admin");</code></pre>

<hr>

<h2>6. Class Name Locator with Password Field</h2>

<pre><code>&lt;input type="password" class="password" placeholder="Enter Password"&gt;</code></pre>

<pre><code>driver.findElement(By.className("password")).sendKeys("admin123");</code></pre>

<hr>

<h2>7. Class Name Locator with Email Field</h2>

<pre><code>&lt;input type="email" class="email-field"&gt;</code></pre>

<pre><code>driver.findElement(By.className("email-field")).sendKeys("[email protected]");</code></pre>

<hr>

<h2>8. Class Name Locator with Search Box</h2>

<pre><code>&lt;input type="search" class="search-box"&gt;</code></pre>

<pre><code>driver.findElement(By.className("search-box")).sendKeys("Selenium WebDriver");</code></pre>

<hr>

<h2>9. Class Name Locator with Button</h2>

<pre><code>&lt;button type="submit" class="login-button"&gt;Login&lt;/button&gt;</code></pre>

<p>Selenium:</p>

<pre><code>driver.findElement(By.className("login-button")).click();</code></pre>

<hr>

<h2>10. Class Name Locator with Checkbox</h2>

<pre><code>&lt;input type="checkbox" class="terms-checkbox"&gt;</code></pre>

<pre><code>WebElement terms = driver.findElement(By.className("terms-checkbox"));

 

if (!terms.isSelected()) {

    terms.click();

}</code></pre>

<hr>

<h2>11. Class Name Locator with Radio Button</h2>

<pre><code>&lt;input type="radio" class="gender-option" value="male"&gt;

&lt;input type="radio" class="gender-option" value="female"&gt;</code></pre>

<p>If multiple elements use the same class, use <code>findElements()</code>:</p>

<pre><code>List&lt;WebElement&gt; genderOptions =

    driver.findElements(By.className("gender-option"));</code></pre>

<hr>

<h2>12. Class Name Locator with Form Fields</h2>

<pre><code>&lt;form&gt;

    &lt;input type="text" class="first-name"&gt;

    &lt;input type="text" class="last-name"&gt;

    &lt;input type="email" class="email-field"&gt;

    &lt;input type="password" class="password-field"&gt;

&lt;/form&gt;</code></pre>

<p>Selenium:</p>

<pre><code>driver.findElement(By.className("first-name")).sendKeys("John");

driver.findElement(By.className("last-name")).sendKeys("Smith");

driver.findElement(By.className("email-field")).sendKeys("[email protected]");

driver.findElement(By.className("password-field")).sendKeys("Pass@123");</code></pre>

<hr>

<h2>13. Class Name Locator with sendKeys()</h2>

<p>The <code>sendKeys()</code> method is used to enter text into input elements.</p>

<pre><code>driver.findElement(By.className("username")).sendKeys("admin");</code></pre>

<hr>

<h2>14. Class Name Locator with clear()</h2>

<p>The <code>clear()</code> method removes existing text from a text field.</p>

<pre><code>WebElement username =

    driver.findElement(By.className("username"));

 

username.clear();

username.sendKeys("newUser");</code></pre>

<hr>

<h2>15. Class Name Locator with click()</h2>

<p>The <code>click()</code> method can be used on buttons, checkboxes, radio buttons, links, and other clickable elements.</p>

<pre><code>driver.findElement(By.className("login-button")).click();</code></pre>

<hr>

<h2>16. Class Name Locator with getText()</h2>

<p>The <code>getText()</code> method retrieves visible text from an element.</p>

<pre><code>String message =

    driver.findElement(By.className("success-message")).getText();

 

System.out.println(message);</code></pre>

<hr>

<h2>17. Class Name Locator with getAttribute()</h2>

<p>The <code>getAttribute()</code> method can be used to retrieve an HTML attribute.</p>

<pre><code>WebElement username =

    driver.findElement(By.className("username"));

 

String value = username.getAttribute("value");

 

System.out.println(value);</code></pre>

<hr>

<h2>18. Class Name Locator with WebElement</h2>

<p>The located element can be stored in a <code>WebElement</code> variable.</p>

<pre><code>WebElement emailField =

    driver.findElement(By.className("email-field"));

 

emailField.sendKeys("[email protected]");</code></pre>

<hr>

<h2>19. Required Selenium Imports</h2>

<pre><code>import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.WebElement;

import org.openqa.selenium.chrome.ChromeDriver;</code></pre>

<hr>

<h2>20. Complete Basic Class Name Program</h2>

<pre><code>import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.chrome.ChromeDriver;

 

public class ClassNameLocatorExample {

 

    public static void main(String[] args) {

 

        WebDriver driver = new ChromeDriver();

 

        driver.get("https://example.com/login");

 

        driver.findElement(By.className("username"))

              .sendKeys("admin");

 

        driver.findElement(By.className("password"))

              .sendKeys("admin123");

 

        driver.findElement(By.className("login-button"))

              .click();

 

        driver.quit();

    }

}</code></pre>

<hr>

<h2>21. Class Name Locator in Login Form</h2>

<p>Consider the following login form:</p>

<pre><code>&lt;form&gt;

    &lt;input type="text" class="username"&gt;

    &lt;input type="password" class="password"&gt;

    &lt;button type="submit" class="login-button"&gt;Login&lt;/button&gt;

&lt;/form&gt;</code></pre>

<p>Selenium automation:</p>

<pre><code>driver.findElement(By.className("username"))

      .sendKeys("admin");

 

driver.findElement(By.className("password"))

      .sendKeys("admin123");

 

driver.findElement(By.className("login-button"))

      .click();</code></pre>

<hr>

<h2>22. Class Name Locator in Registration Form</h2>

<pre><code>&lt;input type="text" class="first-name"&gt;

&lt;input type="text" class="last-name"&gt;

&lt;input type="email" class="email-field"&gt;

&lt;input type="password" class="password-field"&gt;

&lt;input type="password" class="confirm-password"&gt;

&lt;button type="submit" class="register-button"&gt;Register&lt;/button&gt;</code></pre>

<p>Selenium:</p>

<pre><code>driver.findElement(By.className("first-name"))

      .sendKeys("John");

 

driver.findElement(By.className("last-name"))

      .sendKeys("Smith");

 

driver.findElement(By.className("email-field"))

      .sendKeys("[email protected]");

 

driver.findElement(By.className("password-field"))

      .sendKeys("Pass@123");

 

driver.findElement(By.className("confirm-password"))

      .sendKeys("Pass@123");

 

driver.findElement(By.className("register-button"))

      .click();</code></pre>

<hr>

<h2>23. Class Name Locator in Search Form</h2>

<pre><code>&lt;input type="text" class="search-input"&gt;

&lt;button type="submit" class="search-button"&gt;Search&lt;/button&gt;</code></pre>

<pre><code>driver.findElement(By.className("search-input"))

      .sendKeys("Laptop");

 

driver.findElement(By.className("search-button"))

      .click();</code></pre>

<hr>

<h2>24. What is a Class Token?</h2>

<p>An HTML element can contain multiple class names separated by spaces.</p>

<pre><code>&lt;input class="form-control input-field username"&gt;</code></pre>

<p>Here, the element has three class tokens:</p>

<ul>

<li><code>form-control</code></li>

<li><code>input-field</code></li>

<li><code>username</code></li>

</ul>

<p>Each token represents an individual class name.</p>

<hr>

<h2>25. Important Rule: Do Not Pass Multiple Classes to By.className()</h2>

<p>One of the most common mistakes is trying to pass the complete class attribute containing spaces to <code>By.className()</code>.</p>

<p>For example:</p>

<pre><code>&lt;input class="form-control username"&gt;</code></pre>

<p>This is incorrect:</p>

<pre><code>driver.findElement(

    By.className("form-control username")

);</code></pre>

<p><code>By.className()</code> expects a single class name token, not a space-separated list of multiple classes.</p>

<hr>

<h2>26. Correct Way to Use By.className()</h2>

<p>For:</p>

<pre><code>&lt;input class="form-control username"&gt;</code></pre>

<p>You can use one class token:</p>

<pre><code>driver.findElement(By.className("form-control"));</code></pre>

<p>or:</p>

<pre><code>driver.findElement(By.className("username"));</code></pre>

<p>If one class is not sufficiently specific, use a CSS Selector instead.</p>

<hr>

<h2>27. Using CSS Selector for Multiple Classes</h2>

<p>Suppose the element is:</p>

<pre><code>&lt;input class="form-control username"&gt;</code></pre>

<p>A CSS Selector can target both classes:</p>

<pre><code>driver.findElement(

    By.cssSelector(".form-control.username")

);</code></pre>

<p>This is different from <code>By.className()</code>, which accepts one class token.</p>

<hr>

<h2>28. Class Name Locator with findElement()</h2>

<p><code>findElement()</code> returns the first matching WebElement.</p>

<pre><code>WebElement username =

    driver.findElement(By.className("username"));</code></pre>

<p>If Selenium cannot find a matching element in the current browsing context, it can throw <code>NoSuchElementException</code>.</p>

<hr>

<h2>29. Class Name Locator with findElements()</h2>

<p><code>findElements()</code> returns a list of matching WebElements.</p>

<pre><code>List&lt;WebElement&gt; elements =

    driver.findElements(By.className("username"));</code></pre>

<p>If no matching elements are found, an empty list is returned.</p>

<hr>

<h2>30. Difference Between findElement() and findElements()</h2>

<table border="1" cellpadding="8" cellspacing="0">

<tr><th>Feature</th><th>findElement()</th><th>findElements()</th></tr>

<tr><td>Return Type</td><td>WebElement</td><td>List&lt;WebElement&gt;</td></tr>

<tr><td>Multiple Matches</td><td>Returns first matching element</td><td>Returns all matching elements</td></tr>

<tr><td>No Match</td><td>Throws NoSuchElementException</td><td>Returns empty list</td></tr>

<tr><td>Typical Use</td><td>Single target</td><td>Groups of elements</td></tr>

</table>

<hr>

<h2>31. Class Name Locator with Multiple Elements</h2>

<p>Suppose a page contains:</p>

<pre><code>&lt;button class="product-button"&gt;Product 1&lt;/button&gt;

&lt;button class="product-button"&gt;Product 2&lt;/button&gt;

&lt;button class="product-button"&gt;Product 3&lt;/button&gt;</code></pre>

<p>Using <code>findElement()</code>:</p>

<pre><code>WebElement button =

    driver.findElement(By.className("product-button"));</code></pre>

<p>The first matching element is returned.</p>

<p>Using <code>findElements()</code>:</p>

<pre><code>List&lt;WebElement&gt; buttons =

    driver.findElements(By.className("product-button"));</code></pre>

<p>All matching elements are returned.</p>

<hr>

<h2>32. Counting Elements Using Class Name</h2>

<pre><code>List&lt;WebElement&gt; buttons =

    driver.findElements(By.className("product-button"));

 

System.out.println("Number of buttons: " + buttons.size());</code></pre>

<p>This is useful for verifying repeated components on a page.</p>

<hr>

<h2>33. Class Name Locator for Multiple Buttons</h2>

<pre><code>&lt;button class="action-button"&gt;Edit&lt;/button&gt;

&lt;button class="action-button"&gt;Delete&lt;/button&gt;

&lt;button class="action-button"&gt;View&lt;/button&gt;</code></pre>

<pre><code>List&lt;WebElement&gt; buttons =

    driver.findElements(By.className("action-button"));

 

for (WebElement button : buttons) {

    System.out.println(button.getText());

}</code></pre>

<hr>

<h2>34. Class Name Locator for Checkbox Groups</h2>

<pre><code>&lt;input type="checkbox" class="skill"&gt;

&lt;input type="checkbox" class="skill"&gt;

&lt;input type="checkbox" class="skill"&gt;</code></pre>

<pre><code>List&lt;WebElement&gt; skills =

    driver.findElements(By.className("skill"));</code></pre>

<hr>

<h2>35. Selecting Multiple Checkboxes</h2>

<pre><code>List&lt;WebElement&gt; skills =

    driver.findElements(By.className("skill"));

 

for (WebElement skill : skills) {

 

    if (!skill.isSelected()) {

        skill.click();

    }

}</code></pre>

<hr>

<h2>36. Class Name Locator for Radio Buttons</h2>

<pre><code>&lt;input type="radio" class="gender-option" value="male"&gt;

&lt;input type="radio" class="gender-option" value="female"&gt;</code></pre>

<p>Locate all options:</p>

<pre><code>List&lt;WebElement&gt; options =

    driver.findElements(By.className("gender-option"));</code></pre>

<hr>

<h2>37. Selecting a Specific Radio Button by Value</h2>

<pre><code>List&lt;WebElement&gt; options =

    driver.findElements(By.className("gender-option"));

 

for (WebElement option : options) {

 

    if ("female".equals(option.getAttribute("value"))) {

        option.click();

        break;

    }

}</code></pre>

<hr>

<h2>38. Class Name Locator with isSelected()</h2>

<p>The <code>isSelected()</code> method is useful for radio buttons and checkboxes.</p>

<pre><code>WebElement checkbox =

    driver.findElement(By.className("terms-checkbox"));

 

if (!checkbox.isSelected()) {

    checkbox.click();

}</code></pre>

<hr>

<h2>39. Class Name Locator with isDisplayed()</h2>

<pre><code>WebElement message =

    driver.findElement(By.className("success-message"));

 

if (message.isDisplayed()) {

    System.out.println("Message is displayed.");

}</code></pre>

<hr>

<h2>40. Class Name Locator with isEnabled()</h2>

<pre><code>WebElement submit =

    driver.findElement(By.className("submit-button"));

 

if (submit.isEnabled()) {

    System.out.println("Submit button is enabled.");

}</code></pre>

<hr>

<h2>41. Complete State Validation</h2>

<pre><code>WebElement element =

    driver.findElement(By.className("submit-button"));

 

System.out.println("Displayed: " + element.isDisplayed());

System.out.println("Enabled: " + element.isEnabled());

System.out.println("Selected: " + element.isSelected());</code></pre>

<hr>

<h2>42. Class Name Locator with Explicit Wait</h2>

<p>When an element loads dynamically, use an explicit wait.</p>

<pre><code>WebDriverWait wait =

    new WebDriverWait(driver, Duration.ofSeconds(10));

 

WebElement username = wait.until(

    ExpectedConditions.visibilityOfElementLocated(

        By.className("username")

    )

);

 

username.sendKeys("admin");</code></pre>

<hr>

<h2>43. Class Name Locator with ElementToBeClickable</h2>

<pre><code>WebDriverWait wait =

    new WebDriverWait(driver, Duration.ofSeconds(10));

 

WebElement loginButton = wait.until(

    ExpectedConditions.elementToBeClickable(

        By.className("login-button")

    )

);

 

loginButton.click();</code></pre>

<hr>

<h2>44. Required Wait Imports</h2>

<pre><code>import java.time.Duration;

import org.openqa.selenium.support.ui.ExpectedConditions;

import org.openqa.selenium.support.ui.WebDriverWait;</code></pre>

<hr>

<h2>45. Class Name Locator and Dynamic Elements</h2>

<p>Modern web applications often create elements dynamically using JavaScript. The class attribute may be added after page loading.</p>

<pre><code>WebDriverWait wait =

    new WebDriverWait(driver, Duration.ofSeconds(10));

 

WebElement search = wait.until(

    ExpectedConditions.visibilityOfElementLocated(

        By.className("search-box")

    )

);

 

search.sendKeys("Selenium");</code></pre>

<hr>

<h2>46. Class Name Locator and AJAX</h2>

<p>If an AJAX operation adds a new element to the page, the test should wait for the expected condition rather than immediately attempting interaction.</p>

<pre><code>WebElement result = new WebDriverWait(

    driver,

    Duration.ofSeconds(10)

).until(

    ExpectedConditions.visibilityOfElementLocated(

        By.className("search-result")

    )

);

 

System.out.println(result.getText());</code></pre>

<hr>

<h2>47. Class Name Locator and Iframes</h2>

<p>If an element is inside an iframe, switch to the iframe before using the Class Name Locator.</p>

<pre><code>WebElement frame =

    driver.findElement(By.id("loginFrame"));

 

driver.switchTo().frame(frame);

 

driver.findElement(By.className("username"))

      .sendKeys("admin");

 

driver.switchTo().defaultContent();</code></pre>

<hr>

<h2>48. Class Name Locator and Multiple Windows</h2>

<p>If the target element is in another browser window or tab, switch to the appropriate window before locating it.</p>

<pre><code>String originalWindow = driver.getWindowHandle();

 

for (String window : driver.getWindowHandles()) {

 

    if (!window.equals(originalWindow)) {

        driver.switchTo().window(window);

        break;

    }

}

 

driver.findElement(By.className("username"))

      .sendKeys("admin");</code></pre>

<hr>

<h2>49. Class Name Locator and Shadow DOM</h2>

<p>Elements inside a Shadow DOM may require Shadow Root handling. A normal locator from the document context may not directly cross a shadow boundary.</p>

<p>The appropriate Selenium Shadow DOM APIs should be used when the target element belongs to a shadow tree.</p>

<hr>

<h2>50. Class Name Locator with Dropdown</h2>

<p>A standard select element can have a class attribute.</p>

<pre><code>&lt;select class="country-select"&gt;

    &lt;option value="india"&gt;India&lt;/option&gt;

    &lt;option value="usa"&gt;USA&lt;/option&gt;

&lt;/select&gt;</code></pre>

<p>Locate it:</p>

<pre><code>WebElement country =

    driver.findElement(By.className("country-select"));</code></pre>

<p>Use Selenium's <code>Select</code> class:</p>

<pre><code>Select select = new Select(country);

select.selectByValue("india");</code></pre>

<hr>

<h2>51. Import for Select</h2>

<pre><code>import org.openqa.selenium.support.ui.Select;</code></pre>

<hr>

<h2>52. Class Name Locator for Textarea</h2>

<pre><code>&lt;textarea class="address-field"&gt;&lt;/textarea&gt;</code></pre>

<pre><code>driver.findElement(By.className("address-field"))

      .sendKeys("Mumbai, Maharashtra");</code></pre>

<hr>

<h2>53. Class Name Locator for File Upload</h2>

<pre><code>&lt;input type="file" class="resume-upload"&gt;</code></pre>

<pre><code>driver.findElement(By.className("resume-upload"))

      .sendKeys("C:\\files\\resume.pdf");</code></pre>

<hr>

<h2>54. Class Name Locator for Error Messages</h2>

<pre><code>&lt;span class="error-message"&gt;Invalid email&lt;/span&gt;</code></pre>

<pre><code>String error =

    driver.findElement(By.className("error-message"))

          .getText();

 

System.out.println(error);</code></pre>

<hr>

<h2>55. Class Name Locator for Success Messages</h2>

<pre><code>&lt;div class="success-message"&gt;

    Registration successful

&lt;/div&gt;</code></pre>

<pre><code>String message =

    driver.findElement(By.className("success-message"))

          .getText();

 

System.out.println(message);</code></pre>

<hr>

<h2>56. Class Name Locator vs ID Locator</h2>

<table border="1" cellpadding="8" cellspacing="0">

<tr><th>Feature</th><th>ID Locator</th><th>Class Name Locator</th></tr>

<tr><td>Java Method</td><td>By.id()</td><td>By.className()</td></tr>

<tr><td>HTML Attribute</td><td>id</td><td>class</td></tr>

<tr><td>Typical Purpose</td><td>Unique identification</td><td>Grouping/styling/identification</td></tr>

<tr><td>Can Be Shared</td><td>IDs are intended to be unique</td><td>Classes are commonly shared</td></tr>

<tr><td>Multiple Matches</td><td>Usually unexpected</td><td>Very common</td></tr>

</table>

<hr>

<h2>57. Class Name Locator vs Name Locator</h2>

<table border="1" cellpadding="8" cellspacing="0">

<tr><th>Feature</th><th>Class Name</th><th>Name</th></tr>

<tr><td>HTML Attribute</td><td>class</td><td>name</td></tr>

<tr><td>Selenium Method</td><td>By.className()</td><td>By.name()</td></tr>

<tr><td>Common Usage</td><td>Styling and element grouping</td><td>Form controls</td></tr>

<tr><td>Shared Values</td><td>Very common</td><td>Also possible</td></tr>

</table>

<hr>

<h2>58. Class Name Locator vs Tag Name</h2>

<table border="1" cellpadding="8" cellspacing="0">

<tr><th>Feature</th><th>Class Name</th><th>Tag Name</th></tr>

<tr><td>Selenium Method</td><td>By.className()</td><td>By.tagName()</td></tr>

<tr><td>Uses</td><td>class attribute</td><td>HTML element name</td></tr>

<tr><td>Example</td><td>username</td><td>input</td></tr>

</table>

<hr>

<h2>59. Class Name Locator vs XPath</h2>

<table border="1" cellpadding="8" cellspacing="0">

<tr><th>Feature</th><th>Class Name</th><th>XPath</th></tr>

<tr><td>Syntax</td><td>By.className("username")</td><td>By.xpath("//input[@class='username']")</td></tr>

<tr><td>Complexity</td><td>Simple</td><td>Simple to advanced</td></tr>

<tr><td>Text Matching</td><td>No direct support</td><td>Supported</td></tr>

<tr><td>Element Relationships</td><td>No</td><td>Yes</td></tr>

<tr><td>Multiple Conditions</td><td>Limited</td><td>Supported</td></tr>

</table>

<hr>

<h2>60. Class Name Locator vs CSS Selector</h2>

<p>CSS Selectors provide more flexibility when working with multiple classes or combining classes with other attributes.</p>

<p>For example:</p>

<pre><code>&lt;input class="form-control username"&gt;</code></pre>

<p>Single class:</p>

<pre><code>driver.findElement(By.className("username"));</code></pre>

<p>Multiple classes:</p>

<pre><code>driver.findElement(

    By.cssSelector(".form-control.username")

);</code></pre>

<hr>

<h2>61. Class Name Locator and CSS Class Names with Spaces</h2>

<p>Consider:</p>

<pre><code>&lt;button class="btn btn-primary login-button"&gt;Login&lt;/button&gt;</code></pre>

<p>The class attribute contains three class tokens:</p>

<ul>

<li><code>btn</code></li>

<li><code>btn-primary</code></li>

<li><code>login-button</code></li>

</ul>

<p>You can use:</p>

<pre><code>By.className("btn")</code></pre>

<p>or:</p>

<pre><code>By.className("btn-primary")</code></pre>

<p>or:</p>

<pre><code>By.className("login-button")</code></pre>

<p>But do not use:</p>

<pre><code>By.className("btn btn-primary")</code></pre>

<hr>

<h2>62. Class Name Locator with CSS Selector for Multiple Classes</h2>

<p>For an element with:</p>

<pre><code>class="btn btn-primary login-button"</code></pre>

<p>CSS can combine class selectors:</p>

<pre><code>By.cssSelector(".btn.btn-primary.login-button")</code></pre>

<hr>

<h2>63. Class Name Locator and Dynamic Classes</h2>

<p>Some frameworks generate dynamic class names.</p>

<pre><code>&lt;input class="input-48291"&gt;</code></pre>

<p>The class might later become:</p>

<pre><code>&lt;input class="input-73192"&gt;</code></pre>

<p>A locator based on the complete dynamic class may become unreliable.</p>

<hr>

<h2>64. Handling Dynamic Class Names</h2>

<p>When the class changes dynamically, inspect the element for a stable identifier.</p>

<pre><code>&lt;input id="username" class="input-48291"&gt;</code></pre>

<p>If the ID is stable, use:</p>

<pre><code>By.id("username")</code></pre>

<p>Alternatively, a stable CSS or XPath locator can be considered.</p>

<hr>

<h2>65. Class Name Locator and Framework-Generated Classes</h2>

<p>Modern frameworks can generate classes for styling, state, component libraries, or CSS modules. Some generated classes may change between builds.</p>

<p>For maintainable automation, avoid depending on classes that are clearly generated, hashed, or frequently changing unless the application team intentionally treats them as stable test hooks.</p>

<hr>

<h2>66. Class Name Locator in Page Object Model</h2>

<p>Class Name Locators can be stored inside Page Object classes.</p>

<pre><code>public class LoginPage {

 

    private WebDriver driver;

 

    private By username =

        By.className("username");

 

    private By password =

        By.className("password");

 

    private By loginButton =

        By.className("login-button");

 

    public LoginPage(WebDriver driver) {

        this.driver = driver;

    }

 

    public void login(String user, String pass) {

 

        driver.findElement(username)

              .sendKeys(user);

 

        driver.findElement(password)

              .sendKeys(pass);

 

        driver.findElement(loginButton)

              .click();

    }

}</code></pre>

<hr>

<h2>67. Benefits of Class Name Locator in POM</h2>

<ul>

<li>Locators are centralized.</li>

<li>Page classes are easier to maintain.</li>

<li>Test methods become cleaner.</li>

<li>Locator changes can be made in one location.</li>

<li>Common page elements can be reused.</li>

<li>Automation code becomes more readable.</li>

</ul>

<hr>

<h2>68. Class Name Locator with TestNG</h2>

<pre><code>import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.chrome.ChromeDriver;

import org.testng.annotations.Test;

 

public class LoginTest {

 

    @Test

    public void loginTest() {

 

        WebDriver driver = new ChromeDriver();

 

        driver.get("https://example.com/login");

 

        driver.findElement(By.className("username"))

              .sendKeys("admin");

 

        driver.findElement(By.className("password"))

              .sendKeys("admin123");

 

        driver.findElement(By.className("login-button"))

              .click();

 

        driver.quit();

    }

}</code></pre>

<hr>

<h2>69. Class Name Locator with TestNG Assertion</h2>

<pre><code>import org.testng.Assert;

 

WebElement message =

    driver.findElement(By.className("success-message"));

 

Assert.assertTrue(message.isDisplayed());</code></pre>

<hr>

<h2>70. Class Name Locator with Text Validation</h2>

<pre><code>String actualMessage =

    driver.findElement(

        By.className("success-message")

    ).getText();

 

Assert.assertEquals(

    actualMessage,

    "Registration successful"

);</code></pre>

<hr>

<h2>71. Reusable Class Name Utility</h2>

<pre><code>public void enterText(By locator, String text) {

 

    WebElement element =

        driver.findElement(locator);

 

    element.clear();

    element.sendKeys(text);

}</code></pre>

<p>Usage:</p>

<pre><code>enterText(By.className("username"), "admin");

enterText(By.className("email-field"), "[email protected]");</code></pre>

<hr>

<h2>72. Reusable Click Utility</h2>

<pre><code>public void click(By locator) {

    driver.findElement(locator).click();

}</code></pre>

<p>Usage:</p>

<pre><code>click(By.className("login-button"));

click(By.className("submit-button"));</code></pre>

<hr>

<h2>73. Explicit Wait Utility for Class Name</h2>

<pre><code>public WebElement waitForElement(By locator) {

 

    WebDriverWait wait =

        new WebDriverWait(driver, Duration.ofSeconds(10));

 

    return wait.until(

        ExpectedConditions.visibilityOfElementLocated(locator)

    );

}</code></pre>

<p>Usage:</p>

<pre><code>WebElement username =

    waitForElement(By.className("username"));

 

username.sendKeys("admin");</code></pre>

<hr>

<h2>74. Common Exceptions with Class Name Locator</h2>

<table border="1" cellpadding="8" cellspacing="0">

<tr><th>Exception</th><th>Possible Cause</th></tr>

<tr><td>NoSuchElementException</td><td>Incorrect class or element not available</td></tr>

<tr><td>InvalidSelectorException</td><td>Invalid locator syntax or unsupported class input</td></tr>

<tr><td>ElementNotInteractableException</td><td>Element exists but is not interactable</td></tr>

<tr><td>ElementClickInterceptedException</td><td>Another element blocks the target</td></tr>

<tr><td>StaleElementReferenceException</td><td>DOM changed after the element was located</td></tr>

<tr><td>TimeoutException</td><td>Expected wait condition was not satisfied</td></tr>

</table>

<hr>

<h2>75. NoSuchElementException with Class Name</h2>

<p>Example:</p>

<pre><code>driver.findElement(

    By.className("wrong-class")

).click();</code></pre>

<p>If the class does not match any element in the current browsing context, Selenium can throw <code>NoSuchElementException</code>.</p>

<p>Check:</p>

<ul>

<li>The class spelling.</li>

<li>Whether the class is present.</li>

<li>Whether the element has loaded.</li>

<li>Whether the element is inside an iframe.</li>

<li>Whether the class is dynamically generated.</li>

</ul>

<hr>

<h2>76. ElementNotInteractableException</h2>

<p>An element may exist in the DOM but may not be ready for interaction.</p>

<pre><code>driver.findElement(By.className("username"))

      .sendKeys("admin");</code></pre>

<p>Possible causes include hidden elements, disabled controls, overlays, or an incorrect page state.</p>

<hr>

<h2>77. ElementClickInterceptedException</h2>

<p>This can occur when another element is covering the target.</p>

<pre><code>driver.findElement(By.className("submit-button"))

      .click();</code></pre>

<p>Possible causes include:</p>

<ul>

<li>Popup overlays.</li>

<li>Modal dialogs.</li>

<li>Loading screens.</li>

<li>Sticky headers.</li>

<li>Animations.</li>

</ul>

<hr>

<h2>78. StaleElementReferenceException</h2>

<p>A WebElement reference can become stale when the DOM is refreshed or rebuilt.</p>

<pre><code>WebElement username =

    driver.findElement(By.className("username"));

 

driver.navigate().refresh();

 

username.sendKeys("admin");</code></pre>

<p>After the refresh, the old reference may no longer represent the current element. Locate it again when necessary.</p>

<hr>

<h2>79. Class Name Locator for Product Cards</h2>

<p>Suppose an e-commerce page contains:</p>

<pre><code>&lt;div class="product-card"&gt;

    &lt;h2 class="product-title"&gt;Laptop&lt;/h2&gt;

&lt;/div&gt;

 

&lt;div class="product-card"&gt;

    &lt;h2 class="product-title"&gt;Phone&lt;/h2&gt;

&lt;/div&gt;</code></pre>

<p>Locate all product cards:</p>

<pre><code>List&lt;WebElement&gt; products =

    driver.findElements(By.className("product-card"));</code></pre>

<hr>

<h2>80. Reading Product Card Text</h2>

<pre><code>List&lt;WebElement&gt; products =

    driver.findElements(By.className("product-card"));

 

for (WebElement product : products) {

    System.out.println(product.getText());

}</code></pre>

<hr>

<h2>81. Class Name Locator for Product Buttons</h2>

<pre><code>&lt;button class="add-to-cart"&gt;Add to Cart&lt;/button&gt;</code></pre>

<pre><code>driver.findElement(By.className("add-to-cart"))

      .click();</code></pre>

<hr>

<h2>82. Class Name Locator for Multiple Product Buttons</h2>

<pre><code>List&lt;WebElement&gt; buttons =

    driver.findElements(By.className("add-to-cart"));

 

for (WebElement button : buttons) {

    System.out.println(button.getText());

}</code></pre>

<hr>

<h2>83. Class Name Locator for Navigation Links</h2>

<p>Links can also have class attributes.</p>

<pre><code>&lt;a href="/products" class="nav-link"&gt;Products&lt;/a&gt;

&lt;a href="/orders" class="nav-link"&gt;Orders&lt;/a&gt;</code></pre>

<pre><code>List&lt;WebElement&gt; links =

    driver.findElements(By.className("nav-link"));</code></pre>

<hr>

<h2>84. Class Name Locator for Table Actions</h2>

<pre><code>&lt;button class="edit-button"&gt;Edit&lt;/button&gt;

&lt;button class="delete-button"&gt;Delete&lt;/button&gt;</code></pre>

<pre><code>driver.findElement(By.className("edit-button"))

      .click();</code></pre>

<hr>

<h2>85. Class Name Locator in Real-World E-Commerce</h2>

<p>Class Name Locators can be useful for product cards, search fields, category controls, add-to-cart buttons, checkout forms, and validation messages when the application provides stable class names.</p>

<pre><code>driver.findElement(By.className("search-box"))

      .sendKeys("Laptop");

 

driver.findElement(By.className("search-button"))

      .click();

 

driver.findElement(By.className("add-to-cart"))

      .click();

 

driver.findElement(By.className("checkout-button"))

      .click();</code></pre>

<hr>

<h2>86. Class Name Locator in Real-World Registration</h2>

<pre><code>driver.findElement(By.className("first-name"))

      .sendKeys("John");

 

driver.findElement(By.className("last-name"))

      .sendKeys("Smith");

 

driver.findElement(By.className("email-field"))

      .sendKeys("[email protected]");

 

driver.findElement(By.className("password-field"))

      .sendKeys("Pass@123");

 

WebElement terms =

    driver.findElement(By.className("terms-checkbox"));

 

if (!terms.isSelected()) {

    terms.click();

}

 

driver.findElement(By.className("register-button"))

      .click();</code></pre>

<hr>

<h2>87. Class Name Locator in Payment Form</h2>

<pre><code>List&lt;WebElement&gt; paymentOptions =

    driver.findElements(By.className("payment-option"));

 

for (WebElement option : paymentOptions) {

 

    if ("card".equals(option.getAttribute("value"))) {

        option.click();

        break;

    }

}</code></pre>

<hr>

<h2>88. Class Name Locator in Delivery Options</h2>

<pre><code>List&lt;WebElement&gt; deliveryOptions =

    driver.findElements(By.className("delivery-option"));

 

for (WebElement option : deliveryOptions) {

 

    if ("express".equals(option.getAttribute("value"))) {

        option.click();

        break;

    }

}</code></pre>

<hr>

<h2>89. Class Name Locator in Subscription Options</h2>

<pre><code>List&lt;WebElement&gt; plans =

    driver.findElements(By.className("subscription-option"));

 

for (WebElement plan : plans) {

 

    if ("premium".equals(plan.getAttribute("value"))) {

        plan.click();

        break;

    }

}</code></pre>

<hr>

<h2>90. Class Name Locator Decision Flow</h2>

<pre><code>Start

  |

  v

Inspect Web Element

  |

  v

Does it have a class attribute?

  |

  +---- No ----&gt; Consider ID / Name / CSS / XPath

  |

 Yes

  |

  v

Is the class stable?

  |

  +---- No ----&gt; Find another stable locator

  |

 Yes

  |

  v

Is one class token sufficiently specific?

  |

  +---- Yes ----&gt; Use By.className()

  |

  +---- No -----&gt; Use CSS Selector or XPath

                        |

                        v

                  Locate Target

                        |

                        v

                  Perform Action

                        |

                        v

                  Validate Result</code></pre>

<hr>

<h2>91. Class Name Locator Validation Checklist</h2>

<ul>

<li>Inspect the HTML element.</li>

<li>Find the <code>class</code> attribute.</li>

<li>Identify individual class tokens.</li>

<li>Check whether the class is stable.</li>

<li>Check whether multiple elements use the same class.</li>

<li>Use <code>By.className()</code> with one class token.</li>

<li>Do not pass multiple space-separated classes to <code>By.className()</code>.</li>

<li>Use <code>findElements()</code> for repeated elements.</li>

<li>Use CSS Selector when multiple class conditions are required.</li>

<li>Use XPath when complex relationships or conditions are required.</li>

<li>Use explicit waits for dynamic content.</li>

<li>Handle iframes before locating inner elements.</li>

<li>Validate the expected result after performing an action.</li>

</ul>

<hr>

<h2>92. Common Mistakes with Class Name Locator</h2>

<h3>Mistake 1: Passing Multiple Classes</h3>

<pre><code>By.className("btn btn-primary")</code></pre>

<p>This is incorrect because <code>By.className()</code> expects one class name token.</p>

<h3>Mistake 2: Assuming Class Is Unique</h3>

<p>Classes are frequently shared by multiple elements.</p>

<h3>Mistake 3: Using Dynamic Classes</h3>

<p>Generated or hashed class names may change between builds.</p>

<h3>Mistake 4: Ignoring Iframes</h3>

<p>Elements inside an iframe require switching to the frame first.</p>

<h3>Mistake 5: Not Synchronizing Dynamic Elements</h3>

<p>Modern applications may render class-based elements after asynchronous operations.</p>

<hr>

<h2>93. Class Name Locator Best Practices</h2>

<ul>

<li>Prefer stable class names.</li>

<li>Use one class token with <code>By.className()</code>.</li>

<li>Do not rely on unstable generated classes.</li>

<li>Use <code>findElements()</code> when a class is intentionally shared.</li>

<li>Use CSS Selector for combinations of multiple classes.</li>

<li>Use XPath for complex element relationships.</li>

<li>Use explicit waits for dynamic elements.</li>

<li>Store important locators in Page Object classes.</li>

<li>Keep locators readable and meaningful.</li>

<li>Validate the result after interactions.</li>

</ul>

<hr>

<h2>94. Class Name Locator and Maintainability</h2>

<p>A stable class name can make automation scripts easy to read and maintain.</p>

<pre><code>driver.findElement(

    By.className("login-button")

).click();</code></pre>

<p>The locator clearly indicates that the target is the login button.</p>

<hr>

<h2>95. Class Name Locator and Readability</h2>

<p>Readable locators help automation engineers understand the purpose of each test step.</p>

<pre><code>driver.findElement(

    By.className("email-field")

).sendKeys("[email protected]");</code></pre>

<hr>

<h2>96. Class Name Locator and Test Stability</h2>

<p>Test stability depends on the consistency of the application's HTML. A class that remains unchanged across releases can be useful, while a generated class that frequently changes can cause locator failures.</p>

<p>Always inspect the application DOM and understand how its class names are generated before selecting a class-based locator.</p>

<hr>

<h2>97. Class Name Locator Quick Reference</h2>

<table border="1" cellpadding="8" cellspacing="0">

<tr><th>Action</th><th>Example</th></tr>

<tr><td>Locate</td><td>driver.findElement(By.className("username"))</td></tr>

<tr><td>Type</td><td>driver.findElement(By.className("username")).sendKeys("admin")</td></tr>

<tr><td>Clear</td><td>driver.findElement(By.className("username")).clear()</td></tr>

<tr><td>Click</td><td>driver.findElement(By.className("login-button")).click()</td></tr>

<tr><td>Get Text</td><td>driver.findElement(By.className("message")).getText()</td></tr>

<tr><td>Get Attribute</td><td>driver.findElement(By.className("email")).getAttribute("value")</td></tr>

<tr><td>Displayed</td><td>driver.findElement(By.className("message")).isDisplayed()</td></tr>

<tr><td>Enabled</td><td>driver.findElement(By.className("submit")).isEnabled()</td></tr>

<tr><td>Selected</td><td>driver.findElement(By.className("terms")).isSelected()</td></tr>

<tr><td>Multiple Elements</td><td>driver.findElements(By.className("product-card"))</td></tr>

</table>

<hr>

<h2>98. Class Name Locator Best-Practice Summary</h2>

<table border="1" cellpadding="8" cellspacing="0">

<tr><th>Practice</th><th>Recommendation</th></tr>

<tr><td>Stable Class</td><td>Prefer class names that remain consistent.</td></tr>

<tr><td>Single Token</td><td>Pass one class token to By.className().</td></tr>

<tr><td>Multiple Classes</td><td>Use CSS Selector when multiple class conditions are required.</td></tr>

<tr><td>Shared Class</td><td>Use findElements() when multiple elements intentionally share a class.</td></tr>

<tr><td>Dynamic Class</td><td>Consider another stable locator strategy.</td></tr>

<tr><td>Synchronization</td><td>Use explicit waits for dynamically rendered elements.</td></tr>

<tr><td>POM</td><td>Keep important locators inside Page Object classes.</td></tr>

<tr><td>Validation</td><td>Verify the expected result after interactions.</td></tr>

</table>

<hr>

<h2>99. Interview Question: What is a Class Name Locator?</h2>

<p><strong>Answer:</strong> A Class Name Locator is a Selenium WebDriver locator strategy that identifies a web element using the value of its HTML <code>class</code> attribute. In Selenium Java, it is implemented using <code>By.className()</code>.</p>

<hr>

<h2>100. Interview Question: What is the Syntax of Class Name Locator?</h2>

<p><strong>Answer:</strong></p>

<pre><code>driver.findElement(By.className("username"));</code></pre>

<p>For entering data:</p>

<pre><code>driver.findElement(By.className("username"))

      .sendKeys("admin");</code></pre>

<hr>

<h2>101. Interview Question: Can Multiple Elements Have the Same Class?</h2>

<p><strong>Answer:</strong> Yes. Multiple elements commonly share the same class because classes are frequently used for styling and grouping related elements.</p>

<hr>

<h2>102. Interview Question: Can By.className() Accept Multiple Classes?</h2>

<p><strong>Answer:</strong> No. <code>By.className()</code> expects a single class name token. If an element has multiple classes, use one individual class token or use a CSS Selector for a combination of classes.</p>

<hr>

<h2>103. Interview Question: How Do You Locate an Element with Multiple Classes?</h2>

<p><strong>Answer:</strong> Use a CSS Selector when you need to target multiple class tokens.</p>

<pre><code>By.cssSelector(".form-control.username")</code></pre>

<hr>

<h2>104. Interview Question: Class Name vs ID Locator?</h2>

<p><strong>Answer:</strong> ID Locator uses the <code>id</code> attribute, while Class Name Locator uses the <code>class</code> attribute. IDs are intended to uniquely identify elements, whereas classes are commonly shared.</p>

<hr>

<h2>105. Interview Question: Class Name vs XPath?</h2>

<p><strong>Answer:</strong> Class Name is a simple locator for one class token. XPath provides more advanced capabilities such as text matching, relationships, multiple conditions, and navigation through the DOM.</p>

<hr>

<h2>106. Interview Question: Class Name vs CSS Selector?</h2>

<p><strong>Answer:</strong> Class Name is convenient when one class token is sufficient. CSS Selectors provide more flexibility for combining classes, attributes, element types, and other CSS matching patterns.</p>

<hr>

<h2>107. Interview Question: What Happens If a Class Does Not Exist?</h2>

<p><strong>Answer:</strong> If <code>findElement()</code> cannot find a matching element, Selenium can throw <code>NoSuchElementException</code>.</p>

<hr>

<h2>108. Interview Question: How Do You Handle Dynamic Classes?</h2>

<p><strong>Answer:</strong> Inspect the HTML for a stable ID, name, attribute, CSS pattern, XPath relationship, or dedicated test attribute. Avoid relying on classes that are generated or frequently changed.</p>

<hr>

<h2>109. Interview Question: Can Class Name Be Used for Checkboxes?</h2>

<p><strong>Answer:</strong> Yes. If checkboxes share a common class, use <code>findElements(By.className())</code> and identify the required checkbox using another attribute such as <code>value</code>.</p>

<hr>

<h2>110. Interview Question: Can Class Name Be Used for Radio Buttons?</h2>

<p><strong>Answer:</strong> Yes. Multiple radio buttons can share a class. Use <code>findElements()</code> when necessary and inspect attributes such as <code>value</code> to identify the desired option.</p>

<hr>

<h2>111. Interview Question: Can Class Name Locator Be Used with Explicit Wait?</h2>

<p><strong>Answer:</strong> Yes. A Class Name locator can be passed to explicit wait conditions.</p>

<pre><code>WebElement element = new WebDriverWait(

    driver,

    Duration.ofSeconds(10)

).until(

    ExpectedConditions.visibilityOfElementLocated(

        By.className("username")

    )

);</code></pre>

<hr>

<h2>112. Practical Project: Login Automation Using Class Name</h2>

<pre><code>driver.get("https://example.com/login");

 

driver.findElement(By.className("username"))

      .sendKeys("admin");

 

driver.findElement(By.className("password"))

      .sendKeys("admin123");

 

driver.findElement(By.className("login-button"))

      .click();

 

WebElement message =

    driver.findElement(By.className("success-message"));

 

System.out.println(message.getText());</code></pre>

<hr>

<h2>113. Practical Project: Registration Automation</h2>

<pre><code>driver.findElement(By.className("first-name"))

      .sendKeys("John");

 

driver.findElement(By.className("last-name"))

      .sendKeys("Smith");

 

driver.findElement(By.className("email-field"))

      .sendKeys("[email protected]");

 

driver.findElement(By.className("password-field"))

      .sendKeys("Pass@123");

 

driver.findElement(By.className("confirm-password"))

      .sendKeys("Pass@123");

 

WebElement terms =

    driver.findElement(By.className("terms-checkbox"));

 

if (!terms.isSelected()) {

    terms.click();

}

 

driver.findElement(By.className("register-button"))

      .click();</code></pre>

<hr>

<h2>114. Practical Project: Product Selection</h2>

<pre><code>List&lt;WebElement&gt; products =

    driver.findElements(By.className("product-card"));

 

for (WebElement product : products) {

 

    String productName =

        product.findElement(

            By.className("product-title")

        ).getText();

 

    if ("Laptop".equals(productName)) {

 

        product.findElement(

            By.className("add-to-cart")

        ).click();

 

        break;

    }

}</code></pre>

<hr>

<h2>115. Practical Project: Multiple Checkbox Selection</h2>

<pre><code>List&lt;WebElement&gt; skills =

    driver.findElements(By.className("skill"));

 

for (WebElement skill : skills) {

 

    String value =

        skill.getAttribute("value");

 

    if ("java".equals(value) ||

        "selenium".equals(value)) {

 

        if (!skill.isSelected()) {

            skill.click();

        }

    }

}</code></pre>

<hr>

<h2>116. Complete Class Name Locator Example</h2>

<pre><code>import java.time.Duration;

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.WebElement;

import org.openqa.selenium.chrome.ChromeDriver;

import org.openqa.selenium.support.ui.ExpectedConditions;

import org.openqa.selenium.support.ui.WebDriverWait;

 

public class CompleteClassNameExample {

 

    public static void main(String[] args) {

 

        WebDriver driver = new ChromeDriver();

 

        try {

            driver.manage().window().maximize();

            driver.get("https://example.com/login");

 

            WebDriverWait wait =

                new WebDriverWait(driver, Duration.ofSeconds(10));

 

            WebElement username = wait.until(

                ExpectedConditions.visibilityOfElementLocated(

                    By.className("username")

                )

            );

 

            WebElement password =

                driver.findElement(

                    By.className("password")

                );

 

            WebElement loginButton =

                driver.findElement(

                    By.className("login-button")

                );

 

            username.sendKeys("admin");

            password.sendKeys("admin123");

            loginButton.click();

 

            WebElement message = wait.until(

                ExpectedConditions.visibilityOfElementLocated(

                    By.className("success-message")

                )

            );

 

            System.out.println(message.getText());

 

        } finally {

            driver.quit();

        }

    }

}</code></pre>

<hr>

<h2>117. Class Name Locator Automation Workflow</h2>

<pre><code>Start

  |

  v

Open Web Page

  |

  v

Inspect HTML

  |

  v

Find class attribute

  |

  v

Identify individual class token

  |

  v

Is the class stable?

  |

  +---- No ----&gt; Find another stable locator

  |

 Yes

  |

  v

Is one class token sufficient?

  |

  +---- Yes ----&gt; By.className()

  |

  +---- No -----&gt; CSS Selector / XPath

  |

  v

Locate WebElement

  |

  v

Perform Action

  |

  v

Validate Result

  |

  v

End</code></pre>

<hr>

<h2>118. Class Name Locator Final Checklist</h2>

<ul>

<li>Understand the HTML structure.</li>

<li>Identify the target element.</li>

<li>Find the class attribute.</li>

<li>Separate multiple class tokens mentally.</li>

<li>Check whether the class is stable.</li>

<li>Check whether the class is shared.</li>

<li>Use <code>By.className()</code> for a single class token.</li>

<li>Do not pass space-separated class names to <code>By.className()</code>.</li>

<li>Use <code>findElements()</code> for multiple matching elements.</li>

<li>Use CSS Selector for multiple class conditions.</li>

<li>Use XPath for complex relationships.</li>

<li>Use explicit waits for dynamic content.</li>

<li>Handle iframes when required.</li>

<li>Use Page Object Model in larger frameworks.</li>

<li>Validate the result after performing actions.</li>

</ul>

<hr>

<h2>119. Class Name Locator Summary</h2>

<table border="1" cellpadding="8" cellspacing="0">

<tr><th>Topic</th><th>Key Point</th></tr>

<tr><td>Locator</td><td>Class Name Locator identifies elements using the HTML class attribute.</td></tr>

<tr><td>Java Method</td><td>By.className()</td></tr>

<tr><td>Single Class</td><td>Use one class token with By.className().</td></tr>

<tr><td>Multiple Classes</td><td>Use CSS Selector when multiple class tokens are required.</td></tr>

<tr><td>Repeated Elements</td><td>Use findElements().</td></tr>

<tr><td>Dynamic Classes</td><td>Prefer stable attributes or relationships.</td></tr>

<tr><td>Synchronization</td><td>Use explicit waits for dynamic elements.</td></tr>

<tr><td>POM</td><td>Store locators in page classes.</td></tr>

<tr><td>Validation</td><td>Verify the expected result after interaction.</td></tr>

</table>

<hr>

<h2>120. Conclusion</h2>

<p>The <strong>Class Name Locator</strong> is an important Selenium WebDriver locator strategy for identifying web elements through their HTML <code>class</code> attribute. In Selenium Java, the basic syntax is <code>By.className("classValue")</code>.</p>

<p>Class Name Locators are useful for input fields, buttons, checkboxes, radio buttons, product cards, navigation elements, messages, and many other web components. However, class names are commonly shared between multiple elements, so testers should not automatically assume that a class identifies only one element.</p>

<p>One of the most important rules is that <code>By.className()</code> accepts a single class name token. If an element contains multiple classes such as <code>class="form-control username"</code>, do not pass the entire string with spaces to <code>By.className()</code>. Use one class token or switch to a CSS Selector when multiple classes need to be combined.</p>

<p>For reliable automation, prefer stable class names, avoid generated or frequently changing classes, use <code>findElements()</code> when classes are shared, apply explicit waits for dynamic elements, and use Page Object Model to organize locators in larger Selenium projects.</p>

<p>To learn more about Selenium WebDriver, locators, WebElements, TestNG, Page Object Model, automation frameworks, and real-time testing projects, visit the <a href="https://www.justacademy.co/course-detail/selenium-training" target="_blank" rel="noopener noreferrer">JustAcademy's Selenium Training Course</a>.</p>

<p>To explore or register for a course demo, visit <a href="https://www.justacademy.co/register-for-course-demo" target="_blank" rel="noopener noreferrer">Register for Course Demo</a>.</p>

</div>

Previous Next
whatsapp